﻿//-------------------------------------------------------------------------------------------------
// <copyright file="HomeController.cs" company="Kroll Bond Rating Agency, Inc.">
//  Copyright (c) Kroll Bond Rating Agency, Inc.  All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------

namespace StockQuoteWebSite.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using StockQuoteWebSite.Models;
    using StockQuoteWebSite.QuoteServiceReference;

    /// <summary>
    /// Provides methods that respond to requests made to '/Home'
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// Gets the site's homepage.
        /// </summary>
        /// <returns>
        /// a view containing the site's homepage.
        /// </returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Gets a partial view containing basic information and the last ten days of price history
        /// for the stock with the given ticker.
        /// </summary>
        /// <param name="model">
        /// A <see cref="StockModel"/> populated with the <c>TickerSymbol</c> of the stock whose
        /// data is to be retrieved.
        /// </param>
        /// <returns>
        /// a partial view containing the stock's ticker, company name, last traded price, and the
        /// stock's last ten days of price history
        /// </returns>
        public ActionResult GetQuote(StockModel model)
        {
            var client = new QuoteServiceClient();

            Stock serviceResult = client.GetStockWithPriceHistory(
                model.TickerSymbol.ToUpper(),
                DateTime.Now.Subtract(new TimeSpan(10, 0, 0, 0)),
                DateTime.Now);

            StockModel updatedModel = new StockModel()
            {
                TickerSymbol = serviceResult.TickerSymbol,
                CompanyName = serviceResult.Name,
                LastPrice = serviceResult.LastPrice,
                HistoricalPrices = serviceResult.HistoricalPrices.ToDictionary(
                    k => (long)(k.Date.Subtract(DateTime.Parse("1/1/1970")).Ticks) / 10000,
                    v => v.Close),
                HistoricalPricesStartDate = serviceResult.HistoricalPrices.Min(v => v.Date),
                HistoricalPricesEndDate = serviceResult.HistoricalPrices.Max(v => v.Date)
            };

            ViewData.TemplateInfo.HtmlFieldPrefix = "StockChart";
            return this.PartialView("_StockData", updatedModel);
        }
	}
}